document.addEventListener('DOMContentLoaded', function() {
    // 获取 DOM 元素
    const wsUrlInput = document.getElementById('wsUrl');
    const connectButton = document.getElementById('connectButton');
    const disconnectButton = document.getElementById('disconnectButton');
    const connectionStatus = document.getElementById('connectionStatus');
    const commandArea = document.getElementById('commandArea');
    const commandInput = document.getElementById('commandInput');
    const sendCommandButton = document.getElementById('sendCommandButton');
    const debugDataContainer = document.getElementById('debugDataContainer');
    const debugDataElement = document.getElementById('debugData');

    // 初始化状态
    let isConnected = false;

    // 请求当前连接状态
    chrome.runtime.sendMessage({ type: 'get_status' }, (response) => {
        if (response && response.connected) {
            updateConnectionUI(true, response.url);
            loadDebugData();
        }
    });

    // 连接按钮点击事件
    connectButton.addEventListener('click', () => {
        const wsUrl = wsUrlInput.value.trim();
        if (!wsUrl) {
            updateStatusUI('error', '请输入 WebSocket 服务器地址');
            return;
        }

        // 更新 UI 为连接中状态
        updateStatusUI('disconnected', '正在连接...');

        // 发送连接请求到 background 脚本
        chrome.runtime.sendMessage({ type: 'connect', url: wsUrl },
            (response) => {
                if (response && response.success) {
                    updateConnectionUI(true, wsUrl);
                } else {
                    updateStatusUI('error', `连接失败：${response?.error || '未知错误'}`);
                }
            }
        );
    });

    // 断开连接按钮点击事件
    disconnectButton.addEventListener('click', () => {
        chrome.runtime.sendMessage({ type: 'disconnect' }, (response) => {
            if (response && response.success) {
                updateConnectionUI(false);
            } else {
                updateStatusUI('error', `断开连接失败：${response?.error || '未知错误'}`);
            }
        });
    });

    // 发送命令按钮点击事件
    sendCommandButton.addEventListener('click', () => {
        const command = commandInput.value.trim();
        if (!command) {
            return;
        }

        try {
            // 尝试解析为 JSON
            const commandObj = JSON.parse(command);

            // 发送命令到 background 脚本
            chrome.runtime.sendMessage({ type: 'send_command', command: commandObj },
                (response) => {
                    if (response && response.success) {
                        // 清空命令输入框
                        commandInput.value = '';
                    } else {
                        updateStatusUI('error', `发送命令失败：${response?.error || '未知错误'}`);
                    }
                }
            );
        } catch (error) {
            updateStatusUI('error', `无效的 JSON 格式：${error.message}`);
        }
    });

    // 按 Enter 键发送命令
    commandInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            sendCommandButton.click();
        }
    });

    // 更新连接状态 UI
    function updateConnectionUI(connected, url = '') {
        isConnected = connected;

        // 更新按钮状态
        connectButton.disabled = connected;
        disconnectButton.disabled = !connected;

        // 更新 URL 输入框
        if (url) {
            wsUrlInput.value = url;
        }

        // 更新状态显示
        if (connected) {
            updateStatusUI('connected', `已连接到 ${url}`);
            commandArea.classList.remove('hidden');
            debugDataContainer.classList.remove('hidden');
            loadDebugData();
        } else {
            updateStatusUI('disconnected', '未连接');
            commandArea.classList.add('hidden');
            debugDataContainer.classList.add('hidden');
        }
    }

    // 更新状态显示
    function updateStatusUI(status, message) {
        connectionStatus.className = `status ${status}`;
        connectionStatus.textContent = `状态：${message}`;
    }

    // 加载调试数据
    function loadDebugData() {
        chrome.runtime.sendMessage({ type: 'get_debug_data' }, (response) => {
            if (response && response.data) {
                displayDebugData(response.data);
            }
        });
    }

    // 显示调试数据
    function displayDebugData(data) {
        debugDataElement.innerHTML = '';

        if (data.length === 0) {
            const noDataElement = document.createElement('div');
            noDataElement.textContent = '暂无调试数据';
            debugDataElement.appendChild(noDataElement);
            return;
        }

        // 显示最新的 10 条数据
        const recentData = data.slice(-10);

        recentData.forEach((item) => {
            const itemElement = document.createElement('div');
            itemElement.className = 'debug-item';
            itemElement.textContent = JSON.stringify(item, null, 2);
            debugDataElement.appendChild(itemElement);
        });

        // 滚动到底部
        debugDataContainer.scrollTop = debugDataContainer.scrollHeight;
    }

    // 监听来自 background 的消息
    chrome.runtime.onMessage.addListener((message) => {
        if (message.type === 'connection_status') {
            if (message.status === 'connected') {
                updateConnectionUI(true);
            } else if (message.status === 'disconnected' || message.status === 'error') {
                updateConnectionUI(false);
                if (message.error) {
                    updateStatusUI('error', `错误：${message.error}`);
                }
            }
        } else if (message.type === 'debug_data') {
            loadDebugData();
        }
    });
});